import re
import winsound
import os

import tkinter as tk
from tkinter import ttk

def config():
    sounds_path = os.path.join(os.path.dirname(os.path.dirname(os.path.abspath(__file__))), 'sounds')
    CONFIG = {
        "sounds_path": sounds_path,
        "window_width": 450,
        "window_height": 140,

        "blue_color": "#6f9bc6",
        "yellow_color": "#f2993a",

        "sounds": {
            "1":"boom.wav",
            "2":"clap.wav",
            "3":"hihat.wav",
            "4":"kick.wav",
            "5":"openhat.wav",
            "6":"ride.wav",
            "7":"snare.wav",
            "8":"tink.wav",
            "9":"tom.wav",
        }
    }
    return CONFIG

def add_frame(curr_tk):
    frame = tk.Frame(
                    curr_tk, 
                    width=CONFIG.get("window_width"), 
                    height=CONFIG.get("window_height"),
                    background=CONFIG.get("blue_color"))
    frame.grid(row=0, column=0, padx=5, pady=5)

    label = ttk.Label(frame, text='Enter digital number:', background=CONFIG.get("yellow_color"))
    label.grid(row=0, column=0, padx=5, pady=5)

    input_number_str = tk.StringVar()
    result_str = tk.StringVar()

    get_input = ttk.Entry(frame, textvariable=input_number_str)
    get_input.grid(row=0, column=1, padx=5, pady=5)
    my_style = ttk.Style()
    my_style.configure("Custom.TLabel", foreground="white", font=("Arial, 10"), background=CONFIG.get("blue_color"))

    result = ttk.Label(frame, textvariable=result_str, style='Custom.TLabel')
    result.grid(row=2, column=1, padx=5, pady=10)

    def play_music():
        try:
            input_str = input_number_str.get()
            input_number_str.set('')
            result_str.set('')
            re_result = re.match("^[1-9]+$", input_str)
            if not re_result:
                raise ValueError({'code':500, 'msg':'Only numbers from 1-9 can be entered'})
            for i in re_result.group():
                sounds_str = str(os.path.join(CONFIG.get('sounds_path'), CONFIG.get('sounds').get(i)))
                winsound.PlaySound(sounds_str, winsound.SND_FILENAME)
            
            
        except Exception as exce:
            result_str.set("Invalid input")

    button = ttk.Button(frame, text='play', command=play_music)
    button.grid(row=0, column=3, padx=5, pady=5)


def create_tk():
    curr_tk = tk.Tk()
    curr_tk.title("digital music".title())
    curr_tk.config(bg="skyblue")

    screen_width = curr_tk.winfo_screenwidth() # 屏幕的宽
    screen_height = curr_tk.winfo_screenheight() # 屏幕的高
    tk_width, tk_height = CONFIG.get("window_width"), CONFIG.get("window_height")
    tk_x = (screen_width - tk_width) // 2
    tk_y = (screen_height - tk_height) // 2
    curr_tk.geometry(f"{tk_width}x{tk_height}+{tk_x}+{tk_y}")

    add_frame(curr_tk)

    return curr_tk


def run_tk(curr_tk):
    curr_tk.mainloop()

def start():
    new_tk = create_tk()
    run_tk(new_tk)

CONFIG = config()
start()